//
//  RequestManager.m
//  片刻1.0
//
//  Created by lizi on 15/6/10.
//  Copyright (c) 2015年 lizi. All rights reserved.
//

#import "RequestManager.h"

@implementation RequestManager
- (instancetype)initWithRequestURL:(NSString *)urlString requestModel:(RequestModel)requestModel requestParameter:(NSString *)parameter{
    self = [super init];
    if(self){
        _requestURL = urlString;
        _requestModel = requestModel;
        _requestParameter = parameter;
        _parameterDict = [[NSMutableDictionary alloc] init];
    }
    return self;
}
//开始请求
- (void)startRequest{
//    NSURL *url = [NSURL URLWithString:self.requestURL];
//    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
//    if (self.requestModel == POST) {
//        [urlRequest setHTTPMethod:@"POST"];
//        //当字典有值时，把参数字典转化成字符串，并且给参数赋值
//        [self parameterDictToString];
//        [urlRequest setHTTPBody:[_requestParameter dataUsingEncoding:NSUTF8StringEncoding]];
//    }
//    [NSURLConnection connectionWithRequest:urlRequest delegate:self];
    NSURL *url = [NSURL URLWithString:self.requestURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    if (self.requestModel==POST) {
        [request setHTTPMethod:@"POST"];
        [self parameterDictToString];
        [request setHTTPBody:[_requestParameter dataUsingEncoding:NSUTF8StringEncoding]];
    }
    [NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)parameterDictToString{
    if (_parameterDict.count != 0) {
        NSMutableArray *parameterArray = [NSMutableArray array];
        for (NSString *key in _parameterDict) {
            NSString *str = [NSString stringWithFormat:@"%@=%@",key,_parameterDict[key]];
            [parameterArray addObject:str];
        }
        //这个方法会通过给的参数（&）,将数组中的元素以字符串的形式连接起来，最终返回一个字符串
         _requestParameter = [parameterArray componentsJoinedByString:@"&"];
    }
}
#pragma mark - delegate
//当接收到服务器的响应（连通了服务器）时会调用
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.data = [NSMutableData data];
}
//当接收到服务器的数据时会调用（可能会被调用多次，每次只传递部分数据）
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.data appendData:data];
}
//当服务器的数据加载完毕时就会调用
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if (_delegate && [_delegate respondsToSelector:@selector(requestDidFinishWithData:)]) {
        [_delegate performSelector:@selector(requestDidFinishWithData:) withObject:_data];
    }
}
//请求错误（失败）的时候调用（请求超时\断网\没有网\，一般指客户端错误）
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if (_delegate && [_delegate respondsToSelector:@selector(requestError:)]) {
        [_delegate performSelector:@selector(requestError:) withObject:error];
    }
}
@end
